# -*- encoding: utf-8 -*-

"""
@File:      tc_libtdb_libtdb_func_007.py.py
@Time:      2024/04/18 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libtdb_libtdb_func_007.py.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libtdb libtdb-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >ltdb_test7.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tdb.h>
#include <fcntl.h>

// 向TDB数据库中添加一个键值对的函数
int insert_into_tdb(TDB_CONTEXT *tdb, const char *key, const char *value) {
    TDB_DATA tdb_key, tdb_value;
    tdb_key.dptr = (unsigned char *)key;
    tdb_key.dsize = strlen(key) + 1;
    tdb_value.dptr = (unsigned char *)value;
    tdb_value.dsize = strlen(value) + 1;
    
    return tdb_store(tdb, tdb_key, tdb_value, TDB_REPLACE);
}

int main() {
    TDB_CONTEXT *tdb;

    // 正常创建或打开数据库
    tdb = tdb_open("ltdb_test7.tdb", 0, TDB_DEFAULT, O_CREAT | O_RDWR, 0600);
    if (!tdb) {
        fprintf(stderr, "打开数据库失败\\n");
        return EXIT_FAILURE;
    }

    // 正常情况下向数据库添加一个键值对
    if (insert_into_tdb(tdb, "testkey", "testvalue") != 0) {
        fprintf(stderr, "添加数据时发生错误: %s\\n", tdb_errorstr(tdb));
        tdb_close(tdb);
        return EXIT_FAILURE;
    }
    tdb_close(tdb);

    // 尝试以只读方式打开数据库，并执行写操作，预期将产生错误
    tdb = tdb_open("normal_usage.tdb", 0, TDB_DEFAULT, O_RDONLY, 0600);
    if (!tdb) {
        fprintf(stderr, "以只读模式打开数据库失败\\n");
        return EXIT_FAILURE;
    }

    if (insert_into_tdb(tdb, "readonly_testkey", "should_fail") != 0) {
        fprintf(stderr, "预期的写入错误已发生: %s\\n", tdb_errorstr(tdb));
    } else {
        fprintf(stderr, "意外地写入成功（不应该发生）\\n");
    }

    tdb_close(tdb);
    return 0;
}
EOF'''
        self.cmd(cmdline)


    def test(self):
        self.cmd("gcc -o ltdb_test7 ltdb_test7.c -ltdb")
        self.cmd("./ltdb_test7 > libtdb.log 2>&1")
        code, ltdb_result = self.cmd("cat libtdb.log", ignore_status=True)
        self.assertIn('预期的写入错误已发生: write not permitted', ltdb_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf ltdb_test7.c ltdb_test7 ltdb_test7.tdb libtdb.log")
